# 用 bs4 重写
import requests, os
from bs4 import BeautifulSoup

def req(url, direc=True):
    headersvalue = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 Edg/94.0.992.50'
        }
    r = requests.get(url, headers=headersvalue)
    if direc:
        r.encoding = 'gbk'
        soup = BeautifulSoup(r.text, 'lxml')
        return soup
    else:
        return r

def flag(s):
    flag = True
    while flag:
        try:
            n = int(input(s + "\n"))
            flag = False
        except ValueError:
            print('\n输入有误，请输入一个正整数！！！\n')
        except:
            continue
    return n

def get_jpg(index_url):
    n = flag('需要下载多少张壁纸？')
    ndp, i_url = 0, index_url                   # ndp: numbers of downloaded phtots
    for i in range(1, n//19+2):
        print(f'接下来下载所选分类的第 {i} 页')
        node_a = req(i_url).find('div', {'class': 'list'}).find_all('a')
        page_urls = ['http://www.netbian.com'+a.attrs['href'] for a in node_a]
        for page_url in page_urls:
            try:
                attrs = req(page_url).find('div', {'class': 'pic'}).img.attrs
            except requests.exceptions.ConnectionError:
                if page_url == 'http://www.netbian.comhttp://pic.netbian.com/':
                    continue                    # 跳过每页的第三张图片
                else:
                    print('好像发生了未知错误 1 ，，，')
            except:
                print('好像发生了未知错误 2 ，，，')
            jpg_url, jpg_title = attrs['src'], attrs['title']
            if not os.path.exists(r'd:\photo_from_netbian.com'):
                os.mkdir(r'd:\photo_from_netbian.com')
            with open(fr'd:\photo_from_netbian.com\{jpg_title}.jpg', 'wb') as f:
                f.write(req(jpg_url, direc=False).content)
            ndp += 1
            print(f'第 {ndp} 张图片下载完成！')
            if ndp == n:
                break
        if ndp == n:
            break
        i_url = '{}index_{}.htm'.format(index_url, i+1)
    print(f'{n}张图片全部下载完成，默认保存位置是 d:\photo_from_netbian.com')

print('-'*110)
print('网站的壁纸按内容分类，共有 23 种，分别是：')
print('-'*110)
print('1. 日历    2. 动漫    3. 风景    4. 美女    5. 游戏    6. 影视    7. 动态    8. 唯美    9.设计    10.花卉\n')
print('11.动物    12.节日    13.人物    14.美食    15.水果    16.建筑    17.体育    18.军事    19.非主流  20.护眼 \n')
print('21.LOL    22.王者荣耀   23.其他')
print('-'*110)
choice = flag('按照分类下载，输入对应分类序号；随机下载，输入“0”。请输入：')
choices = ['', 'rili/', 'dongman/', 'fengjing/', 'meinv/', 'youxi/', 'yingshi/', 'dongtai/', 'weimei/', 'sheji/', 'huahui/', 
            'dongwu/', 'jieri/', 'renwu/', 'meishi/', 'shuiguo/', 'jianzhu/', 'tiyu/', 'junshi/', 'feizhuliu/', 's/huyan/', 
            's/lol/', 's/wangzherongyao/', 'qita/']
index_url = 'http://www.netbian.com/' + choices[choice]

get_jpg(index_url)

print('-'*110)
close = input('\n回车关闭窗口')